-- setup_buffer_mappings.lua

-- 定义按键映射函数
local function map(mode, lhs, rhs, opts)
  opts = opts or { noremap = true, silent = true }
  vim.api.nvim_set_keymap(mode, lhs, rhs, opts)
end

-- 检查缓冲区是否为 Neo-tree 或 NerdTree 的缓冲区
local function is_tree_buffer(bufnr)
  local buftype = vim.fn.getbufvar(bufnr, "&buftype")
  local filetype = vim.fn.getbufvar(bufnr, "&filetype")
  return (buftype == "nofile" and (filetype == "neo-tree" or filetype == "nerdtree"))
end

-- 切换到对应序号的缓冲区
local function setup_buffer_mappings()
  -- 获取所有列出的缓冲区
  local buffers = vim.fn.getbufinfo({ buflisted = 1 })

  -- 清除旧的映射（只删除存在的映射）
  for i = 1, 9 do
    local status_ok, err = pcall(vim.api.nvim_del_keymap, "n", "," .. i)
    if not status_ok and err ~= "No mapping found" then
      -- print("Could not delete mapping for: " .. ',' .. i)
    end
  end

  -- 为每个有效的缓冲区创建新的映射
  for i, buf in ipairs(buffers) do
    if i <= 9 and not is_tree_buffer(buf.bufnr) then
      map("n", "," .. i, ":buffer " .. buf.bufnr .. "<CR>", { noremap = true })
    end
  end
end

-- 设置自动命令以在缓冲区添加或删除时更新映射
vim.cmd([[
    augroup BufferMappings
        autocmd!
        autocmd BufAdd,BufDelete * lua require('setup_buffer_mappings').setup_buffer_mappings()
    augroup END
]])

-- 立即执行缓冲区映射设置
setup_buffer_mappings()
